import { login, logout, getUserInfo, refreshToken } from '@/api/login'
import { getToken, setToken, setExpiresIn, removeToken } from '@/utils/auth'
import defAva from '@/assets/images/profile.jpg'

const user = {
  state: {
    token: getToken(),
    name: '',
    avatar: '',
    roles: [],
    permissions: [],
    learningRecords: [
      {
        id: 1,
        courseId: 1,
        courseName: '高中数学必修三 - 概率与统计',
        courseImage: 'https://picsum.photos/id/401/800/450',
        progress: 45,
        lastLearnTime: '2023-07-15 14:30',
        totalTime: '12小时30分钟'
      },
      {
        id: 2,
        courseId: 2,
        courseName: '高中物理必修一 - 力学',
        courseImage: 'https://picsum.photos/id/402/800/450',
        progress: 78,
        lastLearnTime: '2023-07-14 16:45',
        totalTime: '18小时15分钟'
      },
      {
        id: 3,
        courseId: 3,
        courseName: '高中化学选修四 - 有机化学基础',
        courseImage: 'https://picsum.photos/id/403/800/450',
        progress: 23,
        lastLearnTime: '2023-07-13 09:20',
        totalTime: '5小时45分钟'
      }
    ],
    orders: [
      {
        id: 10001,
        courseId: 1,
        courseName: '高中数学必修三 - 概率与统计',
        courseImage: 'https://picsum.photos/id/401/800/450',
        price: '¥99',
        orderTime: '2023-06-10 10:25',
        status: 'completed'
      },
      {
        id: 10002,
        courseId: 2,
        courseName: '高中物理必修一 - 力学',
        courseImage: 'https://picsum.photos/id/402/800/450',
        price: '¥129',
        orderTime: '2023-06-15 14:30',
        status: 'completed'
      },
      {
        id: 10003,
        courseId: 3,
        courseName: '高中化学选修四 - 有机化学基础',
        courseImage: 'https://picsum.photos/id/403/800/450',
        price: '¥89',
        orderTime: '2023-07-01 09:15',
        status: 'completed'
      }
    ],
    favoriteCourses: [1, 2, 5],
    favoriteDiscussions: [1, 3],
    favoriteQuestions: [2],
    favoriteNotes: [1, 4],
    userPosts: {
      discussions: [1],
      questions: [2],
      notes: [1, 4],
      comments: [
        { type: 'discussion', id: 1001 },
        { type: 'question', id: 2001 },
        { type: 'note', id: 3001 }
      ]
    }
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_EXPIRES_IN: (state, time) => {
      state.expires_in = time
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    },
    ADD_LEARNING_RECORD(state, record) {
      state.learningRecords.unshift(record);
    },
    UPDATE_LEARNING_RECORD(state, { id, progress, lastLearnTime, totalTime }) {
      const record = state.learningRecords.find(r => r.id === id);
      if (record) {
        if (progress !== undefined) record.progress = progress;
        if (lastLearnTime !== undefined) record.lastLearnTime = lastLearnTime;
        if (totalTime !== undefined) record.totalTime = totalTime;
      }
    },
    ADD_ORDER(state, order) {
      state.orders.unshift(order);
    },
    UPDATE_ORDER_STATUS(state, { id, status }) {
      const order = state.orders.find(o => o.id === id);
      if (order) {
        order.status = status;
      }
    },
    ADD_FAVORITE_COURSE(state, courseId) {
      if (!state.favoriteCourses.includes(courseId)) {
        state.favoriteCourses.push(courseId);
      }
    },
    REMOVE_FAVORITE_COURSE(state, courseId) {
      state.favoriteCourses = state.favoriteCourses.filter(id => id !== courseId);
    },
    ADD_FAVORITE_DISCUSSION(state, discussionId) {
      if (!state.favoriteDiscussions.includes(discussionId)) {
        state.favoriteDiscussions.push(discussionId);
      }
    },
    REMOVE_FAVORITE_DISCUSSION(state, discussionId) {
      state.favoriteDiscussions = state.favoriteDiscussions.filter(id => id !== discussionId);
    },
    ADD_FAVORITE_QUESTION(state, questionId) {
      if (!state.favoriteQuestions.includes(questionId)) {
        state.favoriteQuestions.push(questionId);
      }
    },
    REMOVE_FAVORITE_QUESTION(state, questionId) {
      state.favoriteQuestions = state.favoriteQuestions.filter(id => id !== questionId);
    },
    ADD_FAVORITE_NOTE(state, noteId) {
      if (!state.favoriteNotes.includes(noteId)) {
        state.favoriteNotes.push(noteId);
      }
    },
    REMOVE_FAVORITE_NOTE(state, noteId) {
      state.favoriteNotes = state.favoriteNotes.filter(id => id !== noteId);
    },
    ADD_USER_POST(state, { type, id }) {
      if (type === 'discussion') {
        state.userPosts.discussions.push(id);
      } else if (type === 'question') {
        state.userPosts.questions.push(id);
      } else if (type === 'note') {
        state.userPosts.notes.push(id);
      } else if (type === 'comment') {
        state.userPosts.comments.push(id);
      }
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim()
      const password = userInfo.password
      const code = userInfo.code
      const uuid = userInfo.uuid
      return new Promise((resolve, reject) => {
        login(username, password, code, uuid).then(res => {
          let data = res.data
          setToken(data.access_token)
          commit('SET_TOKEN', data.access_token)
          setExpiresIn(data.expires_in)
          commit('SET_EXPIRES_IN', data.expires_in)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getUserInfo().then(res => {
          const user = res.user
          const avatar = user.avatar == "" ? defAva :  user.avatar;

          if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
            commit('SET_ROLES', res.roles)
            commit('SET_PERMISSIONS', res.permissions)
          } else {
            commit('SET_ROLES', ['ROLE_DEFAULT'])
          }
          commit('SET_NAME', user.userName)
          commit('SET_AVATAR', avatar)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 刷新token
    RefreshToken({commit, state}) {
      return new Promise((resolve, reject) => {
        refreshToken(state.token).then(res => {
          setExpiresIn(res.data)
          commit('SET_EXPIRES_IN', res.data)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_PERMISSIONS', [])
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    },

    // 获取用户学习记录
    fetchLearningRecords({ state }) {
      return Promise.resolve(state.learningRecords);
    },
    
    // 获取用户订单
    fetchOrders({ state }) {
      return Promise.resolve(state.orders);
    },
    
    // 获取用户收藏的课程
    fetchFavoriteCourses({ state, rootState }) {
      const courses = state.favoriteCourses.map(id => rootState.course.courseDetails[id]).filter(Boolean);
      return Promise.resolve(courses);
    },
    
    // 获取用户收藏的讨论
    fetchFavoriteDiscussions({ state, rootState }) {
      const discussions = state.favoriteDiscussions.map(id => rootState.community.discussions[id]).filter(Boolean);
      return Promise.resolve(discussions);
    },
    
    // 获取用户收藏的问题
    fetchFavoriteQuestions({ state, rootState }) {
      const questions = state.favoriteQuestions.map(id => rootState.community.questions[id]).filter(Boolean);
      return Promise.resolve(questions);
    },
    
    // 获取用户收藏的笔记
    fetchFavoriteNotes({ state, rootState }) {
      const notes = state.favoriteNotes.map(id => rootState.community.notes[id]).filter(Boolean);
      return Promise.resolve(notes);
    },
    
    // 获取用户发布的内容
    fetchUserPosts({ state, rootState }) {
      const result = {
        discussions: state.userPosts.discussions.map(id => rootState.community.discussions[id]).filter(Boolean),
        questions: state.userPosts.questions.map(id => rootState.community.questions[id]).filter(Boolean),
        notes: state.userPosts.notes.map(id => rootState.community.notes[id]).filter(Boolean)
      };
      return Promise.resolve(result);
    },
    
    // 收藏/取消收藏课程
    toggleFavoriteCourse({ commit, state }, courseId) {
      if (state.favoriteCourses.includes(courseId)) {
        commit('REMOVE_FAVORITE_COURSE', courseId);
      } else {
        commit('ADD_FAVORITE_COURSE', courseId);
      }
      return Promise.resolve();
    },
    
    // 收藏/取消收藏讨论
    toggleFavoriteDiscussion({ commit, state }, discussionId) {
      if (state.favoriteDiscussions.includes(discussionId)) {
        commit('REMOVE_FAVORITE_DISCUSSION', discussionId);
      } else {
        commit('ADD_FAVORITE_DISCUSSION', discussionId);
      }
      return Promise.resolve();
    },
    
    // 收藏/取消收藏问题
    toggleFavoriteQuestion({ commit, state }, questionId) {
      if (state.favoriteQuestions.includes(questionId)) {
        commit('REMOVE_FAVORITE_QUESTION', questionId);
      } else {
        commit('ADD_FAVORITE_QUESTION', questionId);
      }
      return Promise.resolve();
    },
    
    // 收藏/取消收藏笔记
    toggleFavoriteNote({ commit, state }, noteId) {
      if (state.favoriteNotes.includes(noteId)) {
        commit('REMOVE_FAVORITE_NOTE', noteId);
      } else {
        commit('ADD_FAVORITE_NOTE', noteId);
      }
      return Promise.resolve();
    }
  },

  getters: {
    // 获取学习记录
    learningRecords: state => state.learningRecords,
    
    // 获取订单
    orders: state => state.orders,
    
    // 获取收藏的课程ID列表
    favoriteCourseIds: state => state.favoriteCourses,
    
    // 获取收藏的讨论ID列表
    favoriteDiscussionIds: state => state.favoriteDiscussions,
    
    // 获取收藏的问题ID列表
    favoriteQuestionIds: state => state.favoriteQuestions,
    
    // 获取收藏的笔记ID列表
    favoriteNoteIds: state => state.favoriteNotes,
    
    // 判断课程是否已收藏
    isCourseFavorite: state => courseId => state.favoriteCourses.includes(Number(courseId)),
    
    // 获取用户发布的内容
    userPosts: state => state.userPosts
  }
}

export default user
